﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Data.SqlClient;
using Kators.BusinessObjects;
using Kators.Exceptions;
using Kators.Services;

namespace Kators
{
    public partial class TeamInfo : Form
    {

        private IList<Team> _teams;
        private IList<Status> _teamStatus;
        private List<Player> _players;

        private bool isNew;
        private string TeamLogoFileExt;


        public TeamInfo()
        {
            InitializeComponent();

        }

        private void TeamInfo_Load(object sender, EventArgs e)
        {
            InitFormLayout();
            LoadTeams();

            SetControlsEnable(false);

            // Specify a font for dataGridView 
            using (Font font = new Font(dataGridView1.DefaultCellStyle.Font.FontFamily, 8, FontStyle.Regular))
            {
                dataGridView1.DefaultCellStyle.Font = font;
            }

            if (listBox1.Items.Count > 0)
                listBox1.SelectedIndex = 0;


            //Unselect data grid view
            dataGridView1[1, 0].Selected = true;
            dataGridView1.ClearSelection();

        }

        private void InitFormLayout()
        {

            cmbBoxMonth.DataSource = DateTimeService.GetMonths();
            cmbBoxDay.DataSource = DateTimeService.GetDays();
            cmbBoxYear.DataSource = DateTimeService.GetYears(2010 /*startYear*/, 2020 /*endYear*/);


            GetAllTeams();

            _teamStatus = Status.GetFullTable();
            cmbBoxStatus.DataSource = _teamStatus;
            cmbBoxStatus.DisplayMember = "Description";

            _players = Player.GetFullTable().ToList();

        }

        private void GetAllTeams()
        {
            _teams = Team.GetFullTable(); //("1=1", "teamName");
            listBox1.DataSource = _teams.OrderBy(x => x.TeamName).ToList();
            listBox1.DisplayMember = "teamName";

        }

        private void LoadTeams()
        {

            try
            {

                lbTotalTeams.Text = "Total Number of Teams: " + Team.GetRowCountByCustomQuery("1=1");
                lbActiveTeams.Text = Team.GetRowCountByCustomQuery("statusId='" + Configuration.ActiveStatusId + "'").ToString();
                lbInActiveTeams.Text = Team.GetRowCountByCustomQuery("statusId='" + Configuration.InActiveStatusId + "'").ToString();
                lbDeletedTeams.Text = Team.GetRowCountByCustomQuery("statusId='" + Configuration.DeletedStatusId + "'").ToString();
                lbPendingTeams.Text = Team.GetRowCountByCustomQuery("statusId='" + Configuration.PendingStatusId + "'").ToString();

                SetControlsEnable(false);


            }
            catch (SqlException ex)
            {
                MessageBox.Show("Cannot connect database... \n" + ex.Message + ex.StackTrace);

            }

        }


        private void SetControlsEnable(bool enable)
        {
            ControlsService.SetControls(gBoxTeamInfo, "TextBox", enable);
            ControlsService.SetControls(gBoxTeamInfo, "ComboBox", enable);
            ControlsService.SetControls(gBoxTeamInfo, "Button", enable);
            ControlsService.SetControls(gBoxTeamInfo, "ComboBox", enable);
            ControlsService.SetControls(gBoxConfirm, "Button", enable);

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (listBox1.SelectionMode != SelectionMode.None && _players !=null)
            //{

            updateTeamSummaryView();

            //}
        }


        private void updateTeamSummaryView()
        {

            Configuration.SourceFilePath = null; 

            var selectedTeam = (Team)listBox1.SelectedItem;
            if (selectedTeam != null)
                Configuration.SelectedTeamId = selectedTeam.TeamId;


            txtName.Text = selectedTeam.TeamName;
            txtOwner.Text = selectedTeam.OwnerName;
            txtCoach.Text = selectedTeam.CoachName;


            if (!selectedTeam.Since.Equals(DateTime.MinValue))
            {
                cmbBoxMonth.SelectedIndex = selectedTeam.Since.Month - 1;
                cmbBoxDay.SelectedIndex = selectedTeam.Since.Day - 1;
                cmbBoxYear.SelectedIndex = cmbBoxYear.FindString(selectedTeam.Since.Year.ToString());
            }
            else
            {
                cmbBoxMonth.SelectedIndex = -1;
                cmbBoxDay.SelectedIndex = -1;
                cmbBoxYear.SelectedIndex = -1;

            }

            try
            {
                var teamStatus = _teamStatus.FirstOrDefault(x => x.StatusId == selectedTeam.StatusId);
                cmbBoxStatus.SelectedIndex = cmbBoxStatus.FindString(teamStatus.Description);
            }
            catch (Exception)
            {
                cmbBoxStatus.SelectedIndex = -1;
                cmbBoxStatus.Refresh();
            }

            try
            {
                string pictureFile = selectedTeam.TeamId + selectedTeam.LogoFileExt;
                string pictureFilePath = Path.Combine(Configuration.GetTeamLogoPath(), pictureFile);

                //Configuration.SourceFilePath = pictureFilePath;
                TeamLogoFileExt = selectedTeam.LogoFileExt; 

                //FileStream fs = new FileStream(pictureFilePath, FileMode.Open, FileAccess.Read);
                //Image image = Image.FromStream(fs);
                //pictureBox1.Image = image;
                //fs.Close();

                pictureBox1.Image = FileService.ShowPictureFile(pictureFilePath);


            }
            catch (Exception)
            {
                pictureBox1.Image = new Bitmap(Configuration.GetNoTeamLogoPath());
            }

            if (_players != null)
            {
                var teamPlayers = _players.FindAll(x => x.TeamId == selectedTeam.TeamId);
                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = teamPlayers.OrderBy(x => x.FirstName).ToList();
                gBoxTeamInfo.Text = "Team Summary: " + teamPlayers.Count + " players"; 

            }
        }


        private void btnBrowser_Click(object sender, EventArgs e)
        {

            Configuration.SourceFilePath = FileService.BrowsingFilePath();

            if (Configuration.SourceFilePath != null)
            {
                TeamLogoFileExt = Path.GetExtension(Configuration.SourceFilePath);
                pictureBox1.Image = new Bitmap(Configuration.SourceFilePath);
            }
        }



        private void btnDelete_Click(object sender, EventArgs e)
        {
            var deletedTeam = Team.GetById(Configuration.SelectedTeamId);

            if (deletedTeam != null)
            {
                DialogResult result =
                    MessageBox.Show("Do you really want to delete a team,\"" + deletedTeam.TeamName + "\"?",
                                    "Kators -- Delete A Team", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    deletedTeam.Delete();

                    string fileName = deletedTeam.TeamId + deletedTeam.LogoFileExt;
                    string targetFilePath = Path.Combine(Configuration.GetTeamLogoPath(), fileName);
                    pictureBox1.Image = null;

                    File.Delete(targetFilePath);

                    GetAllTeams();
                    LoadTeams();

                    if (listBox1.Items.Count > 0)
                        listBox1.SelectedIndex = 0;

                }

                ResetComponents();
            }

        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Configuration.SelectedTeamId != Guid.Empty)
            {
                isNew = false;
                SetControlsEnable(true);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            isNew = true;
            ResetComponents();
            SetControlsEnable(true);
        }

        private void ResetComponents()
        {
            errProvider.Clear();

            foreach (Control ctrl in gBoxTeamInfo.Controls)
            {
                if (ctrl.GetType().Name == "TextBox")
                {
                    ctrl.Text = "";
                }
                if (ctrl.GetType().Name == "ComboBox")
                {
                    (ctrl as ComboBox).SelectedIndex = -1;
                }
                if (ctrl.GetType().Name == "PictureBox")
                {
                    (ctrl as PictureBox).Image = null;
                }
                if (ctrl.GetType().Name == "DataGridView")
                {
                    (ctrl as DataGridView).DataSource = null;
                }

            }

            //Configuration.SourceFilePath = null;
            TeamLogoFileExt = null;
            Configuration.SelectedTeamId = Guid.Empty;

        }


        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (isNew)
            {
                var newTeam = new Team();
                Confirm(newTeam);

            }
            else //update
            {
                var selectedTeam = Team.GetById(Configuration.SelectedTeamId);
                Confirm(selectedTeam);

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SetControlsEnable(false);
            GetAllTeams();
        }

        private bool ValidateForm()
        {
            bool doesValidate = true;

            foreach (Control ctrl in gBoxTeamInfo.Controls)
            {
                if (ctrl.GetType().Name == "TextBox")
                {
                    if (ctrl.Text.Equals(String.Empty))
                    {
                        errProvider.SetError(ctrl, "Please fill the form.");
                        doesValidate = doesValidate && false;
                    }
                }
                if (ctrl.GetType().Name == "ComboBox")
                {

                    if ((ctrl as ComboBox).SelectedIndex == -1)
                    {
                        if ((ctrl as ComboBox).Name == "cmbBoxStatus")
                            errProvider.SetError(ctrl, "Please select combox index.");
                        else
                        {
                            errProvider.SetError(cmbBoxYear, "Please select combox index.");
                        }

                        doesValidate = doesValidate && false;
                    }

                }

            }

            return doesValidate;
        }



        private void Confirm(Team team)
        {
            if (ValidateForm())
            {
                team.TeamName = txtName.Text;
                team.OwnerName = txtOwner.Text;
                team.CoachName = txtCoach.Text;

                team.Since = DateTimeService.GetParsedDateTime(cmbBoxMonth.SelectedItem.ToString(),
                                                               cmbBoxDay.SelectedItem.ToString(),
                                                               cmbBoxYear.SelectedItem.ToString());

                var status = cmbBoxStatus.SelectedItem as Status;
                team.StatusId = _teamStatus.First(x => x.Description == status.Description).StatusId;

                team.LogoFileExt = TeamLogoFileExt;

                if (team.Save())
                {


                    if (Configuration.SourceFilePath != null) 
                    {
                        string fileName = team.TeamId + team.LogoFileExt;
                        string targetFilePath = Path.Combine(Configuration.GetTeamLogoPath(), fileName);

                        try
                        {
                            //if (!Configuration.SourceFilePath.Equals(targetFilePath) &&
                            //    Configuration.SourceFilePath != null)
                            File.Copy(Configuration.SourceFilePath, targetFilePath, true);

                        }
                        catch
                        {
                            MessageBox.Show("team logo file copy is failed.");
                        }
                    }

                    GetAllTeams();
                    LoadTeams();
                    SelectCurrentTeam(team);

                    if (isNew)
                    {
                        MessageBox.Show("Congrats! A new team is added.");
                    }
                    else
                    {
                        //MessageBox.Show("A team is updated.");
                        stripStatusLabel.Text = "A team is updated"; 
                    }



                }
                else
                {
                    if (isNew)
                    {
                        MessageBox.Show("Adding a new team into database is failed. Try again?");
                    }
                    else
                    {
                        MessageBox.Show("Updating a team in database is failed. Try again?");
                    }
                }
            }

        }
        private void SelectCurrentTeam(Team team)
        {

            int index = listBox1.FindString(team.TeamName);
            if (index != -1)
                listBox1.SetSelected(index, true);

        }

        #region clear error provider
        private void txtName_TextChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void txtOwner_TextChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void txtCoach_TextChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void cmbBoxMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void cmbBoxDay_SelectedIndexChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void cmbBoxYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        private void cmbBoxStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            errProvider.Clear();
        }

        #endregion







    }
}
